<template>
  <div :bordered="false">
    <!-- 查询区域 -->
    <!-- <div class="table-operator"> -->
      <!-- <a-button type="primary" icon="plus" @click="handleAdd">新增</a-button> -->
       <!-- 高级查询区域 -->
      <!-- <j-super-query :fieldList="fieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query> -->
      <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay" >
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button>批量操作<a-icon type="down" /></a-button>
      </a-dropdown> -->
    <!-- </div> -->
    <!-- table区域-begin -->
    <div>
      <vxe-grid
        ref="vxeTable"
        id="ProcessTable"
        v-bind="options"
        :columns="getColumns"
        :data="dataSource"
        @checkbox-change="onSelectChange"
        @checkbox-all="onSelectChange"
        @sort-change="onSortChange"
        :checkbox-config="{checkMethod: checCheckboxkMethod}"
        @cell-dblclick="cellDblclick"
      >
      <template v-slot:toolbar_buttons>
        <div class="table-operator">
          <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <a-menu slot="overlay" >
              <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
            </a-menu>
            <a-button>批量操作<a-icon type="down" /></a-button>
          </a-dropdown>
        </div>
      </template>
      <template #switch="{row,column}">
        <a-switch :checked="row['formData'][column.property]" :disabled="true" />
      </template>
      <template #uploadImg="{row,column}" >
        <div v-if="Array.isArray(row['formData'][column.property]) && row['formData'][column.property].length > 0" class="j-table-slot-view">
          <img v-for="(item,imgIndex) of row['formData'][column.property]" class="upload-img" :src="item.url" alt=" " :key="imgIndex" :preview="index" v-show="imgIndex===0"/>
        </div>
      </template>
      <template #uploadFile="{row,column}">
        <div v-if="Array.isArray(row['formData'][column.property]) && row['formData'][column.property].length > 0" class="j-table-slot-view">
          <a-button type="primary" icon="download" size="small" ghost @click="downloadRowFile(row['formData'][column.property])">下载</a-button>
        </div>
      </template>
      <template #user="{row, column}">
        <span>{{getRealname(row['formData'][column.property])}}</span>
        <!-- <span>{{JSON.stringify(column)}}</span> -->
      </template>
      <template #dept="{row,column}">
        <span>{{initDepartComponent(row['formData'][column.property])}}</span>
      </template>
      <template #status="{row,column}">
        <span class="status" :class="{yellow:row.status === 1,green:row.status === 2}">{{filterDictTextByCache('bpmn_status', row[column.property])}}</span>
      </template>
      <template #action="{row}">
        <a v-if="row.status === 0 || row.status === 3 || row.status === 5" @click="startInstance(row)">提交</a>
        <a-divider v-if="row.status === 0 || row.status === 3 || row.status === 5" type="vertical" />
        <a v-if="row.status === 0 || row.status === 3 || row.status === 5" @click="handleEdit(row,false)">编辑</a>
        <a  v-if="row.status !== 0 && row.status !== 3 && row.status !== 5" @click="handleEdit(row,true)">详情</a>
        <a-divider v-if="row.status === 0 || row.status === 3 || row.status === 5" type="vertical" />
        <a-popconfirm
          v-if="row.status === 0 || row.status === 3 || row.status === 5"
          title="确定删除吗?"
          @confirm="() => handleDelete(row.formDataId)"
        >
          <a >删除</a>
        </a-popconfirm>
      </template>
      <template v-slot:pager>
        <vxe-pager
          :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
          :current-page.sync="ipagination.currentPage"
          :page-size.sync="ipagination.pageSize"
          :total="ipagination.total"
          @page-change="handlePageChange"
        >
        </vxe-pager>
      </template>
    </vxe-grid>
    </div>
    <!-- 表单弹窗区域 -->
    <j-modal
      width="80%"
      :title="kfbTitle"
      :visible.sync="desformApplyVisible"
      :fullscreen.sync="fullscreen"
      :switch-fullscreen="switchFullscreen"
      :destroyOnClose="true"
      :maskClosable="false"
    >
      <template slot="footer">
        <a-button key="back" @click="desformApplyHandleCancel">
          取消
        </a-button>
        <a-button key="submit" v-if="!disabledAll" type="primary" :loading="confirmLoading" @click="desformApplyHandleOk">
          确定
        </a-button>
      </template>
      <a-spin size="large" :spinning="spinning">
        <k-form-build ref="kfb" :value="formData" :disabled="disabledAll" />
      </a-spin>
    </j-modal>
    <task-modal ref="taskModal" title="历史" :taskData="taskData" type="history"></task-modal>
  </div>
</template>
<script>
import { VxeTableMixin } from '@/mixins/VxeTableMixin'
import { saveOrUpdate, startInstance } from '@/api/process'
import { ProcessTableMixins } from './mixins/ProcessTableMixins'
import { getAction } from '@/api/manage'
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
import { KFormBuild } from '@/components/k-form-design/index'
import { mapGetters } from 'vuex'
import taskModal from '@/views/modules/task/modal/TaskModal'
import ColSetting from '@/components/custom/ColSetting'
import JSuperQuery from '@/components/jeecg/JSuperQuery'
export default {
  name: 'ProcessTable',
  components: {
    KFormBuild,
    taskModal,
    ColSetting,
    JSuperQuery
  },
  mixins: [VxeTableMixin, ProcessTableMixins],
  props: {
    modelId: { // 流程modelId
      type: String,
      default: ''
    },
    businessId: {// 来源数据id
      type: String,
      default: ''
    },
    sourceCategory: {// 来源单据类型
      type: String,
      default: ''
    },
    headers: {// 是否展示table上部head
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      fullscreen: false,
      switchFullscreen: true,
      kfbTitle: '新增',
      desformApplyVisible: false,
      disabledAll: false, // 表单禁用控制
      taskData: {}, // 流程数据
      disableMixinCreated: true, // 禁止mixin自动加载
      url: {
        list: '/activiti/formData/list',
        deleteBatch: '/activiti/formData/deleteBatch',
        delete: '/activiti/formData/delete',
        getKfdJson: '/activiti/form/getFormByProcessDefinitionId',
        getNewKfdJson: '/activiti/form/getFormDeploymentByModelId' // 获取组件自定义表单
      },
      rootUrLReplace: '/ProcessList/', // 根据这个截取url参数
      spinning: false,
      syncLoading: false,
      confirmLoading: false
    }
  },
  methods: {
    ...mapGetters(['userInfo']),
    filterDictTextByCache: filterDictTextByCache,
    getQueryParams() {
      return {
        businessId: this.businessId,
        pageNo: this.ipagination.currentPage,
        pageSize: this.ipagination.pageSize
      }
    },
    getCheckboxProps(record) {
      return {
        props: {
          disabled: !(record.status === 0 || record.status === 3) // Column configuration not to be checked
        }
      }
    },
    handleEdit(record, disabled) { // 编辑流程
      this.disabledAll = disabled
      this.taskData = record
      this.kfbTitle = '编辑'
      this.getKfdJson(record)
      this.desformApplyVisible = true
    },
    async getKfdJson(item) { // 不同版本流程获取不同版本
      try {
        this.spinning = true
        const res = await getAction(this.url.getKfdJson, { modelId: item.modelId, processDefinitionId: item.processDefinitionId })
        if (res.success) {
          if (!res.result) {
            return this.$message.warning('该工单的未设计表单')
          }
          this.formData = JSON.parse(res.result.htmlJson)
          this.$nextTick(() => {
            this.$refs.kfb.setData(item.formData)
          })
          this.spinning = false
        } else {
          this.$message.warning(res.message)
        }
      } catch (err) {
        console.log(err)
      }
    },
    handleAdd() { // 新增流程
      if (!this.modelData.processDefinitionId) {
        this.$message.warning('请发布流程再新增')
        return false
      }
      this.disabledAll = false
      this.kfbTitle = '新增'
      this.taskData = {}
      this.formData = this.newFormData
      this.desformApplyVisible = true
    },
    async desformApplyHandleOk() { // 流程表单保存
      try {
        const formData = await this.$refs.kfb.getData()
        if (!this.modelData.processDefinitionId) {
          this.$message.warning('请先发布流程')
          return false
        }
        this.confirmLoading = true
        const params = {
          modelId: this.modelData.modelId,
          formId: this.modelData.id,
          processDefinitionId: this.modelData.processDefinitionId,
          formData: JSON.stringify(formData),
          id: this.taskData.formDataId,
          type: 1
        }
        if (this.taskData.formDataId) {
          params.category = this.taskData.category
          params.businessId = this.taskData.businessId
        } else {
          params.businessId = this.businessId // 来源数据id
          params.category = this.sourceCategory// 来源数据类型
        }
        const res = await saveOrUpdate(params)
        if (res.success) {
          this.desformApplyVisible = false
          this.$message.success('保存成功')
          this.loadData()
          this.resetLoading()
        } else {
          this.$message.warning(res.message)
        }
      } catch (err) {
        console.log(err)
      }
    },
    resetLoading() {
      setTimeout(() => {
        this.confirmLoading = false
      }, 60)
    },
    desformApplyHandleCancel() { // 流程弹窗取消
      this.desformApplyVisible = false
    },
    startInstance(item) { // 提交流程
      if (!this.syncLoading) {
        this.syncLoading = true
        startInstance({
          modelId: item.modelId,
          formDataId: item.formDataId,
          processDefinitionId: item.processDefinitionId
        }).then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.loadData()
            this.syncLoading = false
          } else {
            this.$message.warning(res.message)
          }
        })
      }
    },
    handleHistory(data) { // 点击查看进度
      this.taskData = data
      this.$refs.taskModal.editModalVisible = true
    },
    cellDblclick({ row }) {
      if (row.status !== 0) {
        this.taskData = row
        this.$refs.taskModal.editModalVisible = true
      } else {
        this.$message.warning('该单据未提交')
      }
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
  .j-table-slot-view {
    font-size: 12px;
    font-style: italic;
    .upload-img {
      max-width: 80px;
      max-height: 18px;
    }
  }
  .status{
    padding: 3px 5px;
    border-radius: 5px;
  }
  .yellow{
    background-color: yellow;
    color:#6d5c5c
  }
  .green {
    background-color: #38e038;
    color:#fff
  }
</style>
